#!/usr/bin/env python

# copyright 2010 Studio Cypher, LLC
# developer: Will Emigh
# projects@studiocypher.com

from models import Account

from datetime import datetime
from google.appengine.api import users

# Returns an Account or None based on a Google User
# Takes an optional boolean about whether or not to update the account's
#  last action field; default is False
def get_account_from_user(user, update = False):
    if user == None:
        return None

    query = Account.all()
    query.filter('user =', user)
    results = query.fetch(1)
    for result in results:
        if update:
            result.last_action = datetime.today()
            result.put()
        return result
    return None

def user_required(handler_method):
  """A decorator to require that a user be logged in to access a handler.
  Expands on Google's login_required by also checking to see if they have an
  account in our system

  To use it, decorate your get() method like this:

    @login_required
    def get(self):
      user = users.get_current_user(self)
      self.response.out.write('Hello, ' + user.nickname())

  We will redirect to a login page if the user is not logged in. We always
  redirect to the request URI, and Google Accounts only redirects back as a GET
  request, so this should not be used for POSTs.
  """
  def check_login(self, *args):
    if self.request.method != 'GET':
        raise webapp.Error('The user_required decorator can only be used for'
                         ' GET requests')
    user = users.get_current_user()
    # If they're not logged in, redirect to the login screen
    if not user:
        self.redirect(users.create_login_url(self.request.uri))
        return
    else:
        # If they are logged in, check to see if they've logged in before
        # If they haven't show them the TOS page
        
        account = get_account_from_user(user)
        if not account:
            self.redirect("/accounts/new")
            return
        
        # If they have, do whatever the parent wants
        handler_method(self, *args)

  return check_login